﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using Dac.DAL;
using Dac.DAL.Repositories;
using Dac.Entities;
using Dac.Code;

namespace Dac.Admin
{
    public partial class ProductList : BaseDataPage
    {
        private string ProductPath 
        {
            get
            {
                return MapPath("~/Files/Products/");
            }
        }
        private string ProductPathUrl
        {
            get
            {
                return ResolveClientUrl("~/Files/Products/");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        public override void LoadData()
        {
            using (var repo = RepositoryFactory.ResolveRepository<ProductRepository>())
            {
                grid.DataSource = repo.FindAll();
                grid.DataBind();
            }
        }

        protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            LoadData();
        }

        protected void grid_RowCommand(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            using (var repo = RepositoryFactory.ResolveRepository<ProductRepository>())
            {
                switch (e.CommandName)
                {
                    case "delete":
                        repo.Delete(id);

                        try
                        {
                            string filesPath = Path.Combine(ProductPath, id.ToString());
                            DirectoryInfo dir = new DirectoryInfo(filesPath);
                            dir.Delete(true);
                        }
                        catch (Exception ex)
                        {
                        }

                        break;
                }
            }
            LoadData();
        }

        protected void grid_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Product item = (Product)e.Row.DataItem;

                Image img = (Image)e.Row.FindControl("imgPreviewImage");
                if (string.IsNullOrEmpty(item.PreviewImage))
                    img.Visible = false;
                else
                    img.ImageUrl = ProductPathUrl + item.ProductId.ToString() + "/" + item.PreviewImage;

                ImageButton ibtn = (ImageButton)e.Row.FindControl("lbtnDelete");

                ibtn.Visible = true; //item.CanDelete;
            }
        }        
    }
}